var KOA     	= KOA || {};


KOA.ShopNavigation = function() {

	var nav 			= $(this);
	var win				= $(window);
	var win_height		= win.height();

	var onWindowResize = function() {
		win_height		= win.height();
	};

	var onWindowScroll = function() {

		var top 		= win.scrollTop();	
		// Toggle header sticky
		if (top >= 40) {
			nav.addClass('fixed');
		} else {
			nav.removeClass('fixed');		
		}	
	
	};

	// Initialize
	return (function() {
	
		// Attach scroll handler, this is where all the good stuff happens
		win.scroll(onWindowScroll).trigger('scroll');
		
		// If window resizes we need to cache the new height
		win.resize(onWindowResize);

	})();

};


KOA.Nagivation = function() {
	
	var nav 			= $(this);
	var win				= $(window);
	var win_height		= win.height();
	var nav_items 		= nav.find('A[href^="#"]');
	var current			= '';
	var top_threshold	= 200;
	var scroll_prev		= 0;
	var loaded			= false;
	var load_curtain	= $('#loading');
	var loaded_count    = 0;
	
	var sections		= {
	                      // Top Position, Bottom Position, Is Loaded, Animation Callback
		'top' 			: [0, 842, false, KOA.SectionAnimations.top]
		, 'nutrition' 	: [843, 1742, false, KOA.SectionAnimations.nutrition]
		, 'begood' 		: [1743, 2628, false, KOA.SectionAnimations.begood]
		, 'locations' 	: [2629, 3556, false, KOA.SectionAnimations.locations]
		, 'buy' 		: [3557, 4246, false, KOA.SectionAnimations.buy]
		, 'contact' 	: [4247, 6000, false, null]
    };


	var onWindowResize = function() {
		win_height		= win.height();
	};
	
	var onWindowScroll = function() {
		
		var top 		= win.scrollTop();	
		var bottom 		= top + win_height;
		//var delta 		= top - scroll_prev;
		//var direction	= (delta >= 0) ? 'down' : 'up';
		var active		= false;

		// Toggle header sticky
		/*
		if (top >= 40) {
			nav.addClass('fixed');
		} else {
			nav.removeClass('fixed');		
		}	
		*/

		// If it's srolling to a section don't swap active states
		if (KOA.Prefs.animating == true) return;

		// Detect current active section
		jQuery.each(sections, function(name, params) {
		
			// If top of element is within x pixel of top
			if (params[0] <= (top + top_threshold)) {
				active = name;
			}

			// Top of element is at or above top of window
			if (params[0] <= top) {
				active = name;
			}

			// Bottom is off edge, active and stop looking
			if (params[1] > (top+win_height)) {
				return false;
			}

		});

		if (active && active != current) {

			current = active;
			nav_items.removeClass('active')
			nav_items.filter('.'+active).addClass('active');
			
            if (jQuery.browser.msie != true) history.pushState(null, null, '#'+active);
        
            // Do we need to play the intro animation?
            if (sections[active][2] === false) {
                sections[active][2] = true;
                if (jQuery.isFunction(sections[active][3])) {
                    setTimeout(function() {
                        sections[active][3]();            
                    }, 200);
                }
            }            

		};
		
	};
	
	var onNavclick	= function(e) {
		e.preventDefault();
		e.stopPropagation();
		
		var section = $(this).attr('href').split('#')[1];
		
		if (!section) return;

		var body	= $('HTML,BODY');				
		var loc		= (sections[section]) ? sections[section][0] : 0;
			
		// Set animating flag so active states won't swap
		KOA.Prefs.animating = true;
		
		// Set this state to active right away
		nav_items.removeClass('active');
		$(this).addClass('active');
		
		// Scrooooooooll			
		body.stop(true).animate({scrollTop:loc}, {duration: 750, easing: 'easeInQuad', complete: onNavClickComplete});

	};
	
	var onNavClickComplete = function() {
	
		// We are done animating
		KOA.Prefs.animating = false; 
		// Trigger scroll to update hash
		win.trigger('scroll');			
	
	};
	
	var onSiteLoad = function() {
	
	    loaded_count++;
	    
	    if (loaded_count < 2) return;

		// Attach scroll handler, this is where all the good stuff happens
		win.scroll(onWindowScroll).trigger('scroll');
		
		// Attach click handler to navigation items
		nav_items.click(onNavclick);
		
		// If window resizes we need to cache the new height
		win.resize(onWindowResize);

		// Hide the loading curtain and turn back on scrolling
		load_curtain.fadeOut();
		KOA.$Body.addClass('loaded');
	
	};

	

	// Initialize
	return (function() {
	
		KOA.Utils.preload($('IMG'), {onComplete:onSiteLoad});
		KOA.Utils.preload($('.preload'), {onComplete:onSiteLoad, type: 'bg', delay:500});

	})();


};


KOA.countUp = function(container, end, complete) {

    var current = 0;
    var timer;
    
    var count = function() {
        current++;
        container.html((current).toString().replace('0','O'));
        if (current == end) {
            if (complete) complete();
            clearInterval(timer);
        }
    };
    
    timer = setInterval(count, 100);

};


KOA.spriteFader = function(container, delay, speed) {
    
    var sprite_src          = container.find('IMG').attr('src');
    var sprite_height       = container.find('IMG').height();

    if (!sprite_src) return;
    container.html('').html('<div class="current"></div><div class="next"></div>');

    var container_height    = container.height();
    var container_width     = container.width();
    var delay               = delay || 800;
    var speed               = speed || (delay*.75);
    var offset              = container_height;
    
    var panel_props         = {width: container_width, height: container_height, position: 'absolute', top: 0, left: 0, zIndex: 1, 'background-image': 'url("'+sprite_src+'")', 'background-position':'0 '+offset+'px', opacity: 0};

    var current_state       = container.find('.current').css(panel_props);
    var next_state          = container.find('.next').css(panel_props);
    var pos                 = 0;
    var moves               = (sprite_height / offset);
    
    var timer;
    
    var startFade = function() {
    
        // Set up next move, position over current one        
        next_state.css({zIndex: 2, 'background-position': '0 -'+(pos*offset)+'px', opacity: 0});

        // Start next fade        
        next_state.animate({opacity: 1}, speed, endFade);
        
        pos++;
    
    };

    var endFade = function() {
    
        // Trigger 'individual' event with position
        container.trigger('KOA.spriteFader::fade', [pos]);

        // Housekeeping, apply current state on bottom panel and remove fader before next move
        current_state.css({'background-position': next_state.css('background-position'), opacity: 1});
        next_state.css({opacity: 0});    
        
        // Is this the last move of sequence
        if (pos >= moves) endSequence();
    
    };

    var endSequence = function() {
        
        // Stop moving please
        clearTimeout(timer);

        next_state.remove();

        // Trigger 'finish' event once the last fade is complete
        container.trigger('KOA.spriteFader::finish');

    };
    
	// Initialize
    timer = setInterval(startFade, delay);

};


KOA.SectionAnimations = new function() {

    this.top = function() {
    
        var section     = $('#whatis');
        var item1      = section.find('.image IMG');
        var item2      = section.find('.content_curtain');
        
        var item3      = section.find('.content');
        var item4      = section.find('.content P');
        
        // Set sizes, this helps animation performance
        KOA.Utils.setExplicitSize(item3);
        KOA.Utils.setExplicitSize(item4);
        
        // Pre animate
        item3.css({position: 'relative', top: 20});
        
        // Animate
        item2.delay(150).animate({opacity: 0}, 800);
        item1.animate({opacity: 1}, 1500);
    
    };
    

    this.nutrition = function() {
        
        var section     = $('#nutrition');

        var image       = section.find('.image');
        var image_leaf1  = section.find('.image_leaf.one');
        var image_leaf2  = section.find('.image_leaf.two');
        var image_leaf3  = section.find('.image_leaf.three');

        var count1  = section.find('.image_stat.one');
        var count2  = section.find('.image_stat.two');
        var count3  = section.find('.image_stat.three');
        
        image_leaf1.animate({rotate: '35deg', scale: '.3'}, 1);        
        image_leaf2.animate({rotate: '35deg', scale: '.3'}, 1);        
        image_leaf3.animate({rotate: '35deg', scale: '.3'}, 1);

        new KOA.spriteFader(image, 200);
        
        image_leaf1.delay(800).animate({opacity: 1, rotate: '0deg', scale: '1'}, 700, 'easeOutBounce');
        image_leaf2.delay(1200).animate({opacity: 1, rotate: '0deg', scale: '1'}, 700, 'easeOutBounce');
        image_leaf3.delay(1000).animate({opacity: 1, rotate: '0deg', scale: '1'}, 700, 'easeOutBounce');

        setTimeout(function() {
            new KOA.countUp(count1, 10, function() {
                });
            new KOA.countUp(count2, 9, function() {
                });
            count3.html('O');
        }, 600);


        /*

        var bg2         = section.find('.bg2');
        var bg3         = section.find('.bg3');
        var bg4         = section.find('.bg4');

        bg2.delay(200).animate({opacity: 1});
        bg3.delay(400).animate({opacity: 1});
        bg4.delay(600).animate({opacity: 1});
        
        */

    
    };


    this.buy = function() {
    
        var section     = $('#buy');
        var item1      = section.find('.image IMG');
        //var item2      = section.find('.shadow IMG');
        var item3      = section.find('.content');
        
        // Set sizes, this helps animation performance
        KOA.Utils.setExplicitSize(item1);

        item1.animate({opacity: 1}, 600);
        //item2.delay(330).animate({opacity: 1});

        item3.animate({opacity: 1}, 600);

    
    };
    

    this.begood = function() {
    
        var section             = $('#begood');

        var content             = section.find('.content');
        var animation_leaf      = section.find('.animation_leaf');
        var animation_drop      = section.find('.animation_drop');
        var animation_bottle    = section.find('.animation_bottle');
        var labels              = section.find('.labels');
        
        // Fade in title and text
        content.animate({opacity: 1}, 600);
            
        // Fade in watercolor bits, it can happen all at the same time
        new KOA.spriteFader(animation_leaf, 200);
        new KOA.spriteFader(animation_bottle, 200);            
        new KOA.spriteFader(animation_drop, 200);
        
        // Wait a little while and then it's time to load the captions
        labels.delay(400).animate({opacity: 1});
    
    };


    this.locations = function() {
    
        var section      = $('#locations');
        var animation    = section.find('.animation');
        var content      = section.find('.content');

        // When sequence is complete swap it out for interactive map
        animation.on('KOA.spriteFader::finish', function(){ 
            section.find('.map').css('opacity', 1);
            animation.fadeOut(function() {animation.remove(); }); 
        });

        // When sequence on postion 3 we need to start showing the title
        animation.on('KOA.spriteFader::fade', function(e, pos){ 
            if (pos == 3) content.animate({opacity: 1}, 800);
        });
        
        // Start sequence
        new KOA.spriteFader(animation, 200);
    
    };


};


KOA.Locations = function() {

	var section 	= $(this);
	var modal		= section.find('.modal');
	var modal_frame = section.find('.modal .frame');
	var links		= section.find('.map A');
	
	var logos_load	= false;
	var logos_url	= '/pages/locations-logos';

	var hideModal = function(e) {
		e.preventDefault();
		e.stopPropagation();

	    KOA.$Body.unbind('click', hideModal);

//modal_frame.html('');
		modal.hide();	
	
	}
	
	var loadLogos = function() {

		// Ajax time
		$('#locations_modal_logos').load(logos_url+' #page_content', function() {
			logos_load = true;
		});
	
	};
	
	var showModal = function(e) {
		e.preventDefault();
		e.stopPropagation();
		
		var region 	= $(this);
		var href 	= region.data('href');
		
		// Get the modal ready for new content and show loading animation.
//modal_frame.html('');
//modal.addClass('loading');
		modal.show();
		
		// We should close the modal when you click outside
	    KOA.$Body.bind('click', hideModal);
		
return;
        
		// Get the logos, but we only need to do this once
		if (!logos_load) loadLogos();

		// Make sure the modal is in viewport
		$('HTML,BODY').animate({scrollTop:2784}, {duration: 750, easing: 'easeInQuad'});
		
 		// Add in surrounding html before we make a request
		modal_frame.html('<a href="#" class="next"></a>'
						+ '<a href="#" class="prev"></a>'
						+ '<h3>'+region.data('title')+'</h3>'
						+ '<div class="pages">'
						+ '<div class="slider" id="locations_modal_content"></div>'
						+ '</div>');
		
		// Ajax time
		$('#locations_modal_content').load(href+' #page_content', function() {

			// Remove the CMS instructional alert
			if ((alert = modal_frame.find('.alert'))) alert.remove();

  			// Wrap locations in groups of 6
  			var locs 		= modal_frame.find('.location');
			var locs_len 	= locs.length;
			var per_page	= 6;
			for (var i = 0; i < locs_len; i+=per_page) {
				locs.filter(':eq('+i+'),:lt('+(i+per_page)+'):gt('+i+')').wrapAll('<div class="page">');
			}
			
			if (locs_len > per_page) {
				// Init slideshow JS	
				modal_frame.find('#page_content').cycle({
					next: modal_frame.find('.next')
					, prev: modal_frame.find('.prev')
					, fx: 'scrollLeft'
					, timeout: 0
					});				
			} else {
				// Just one page, hide the controls
			  	modal_frame.find('.next').hide();
			  	modal_frame.find('.prev').hide();
			}
			
			// Ready to go, remove loader and show the div
			setTimeout(function() {modal.removeClass('loading');}, 500);

		});
	
	};

    var onLinkOver = function() {
        $(this).find('SPAN').stop(true,true).fadeIn(300);    
    };

    var onLinkOut = function() {
        $(this).find('SPAN').stop(true,true).fadeOut(200);
    };

	// Initialize
	return (function() {
	
		section.find('A.close').click(hideModal);
	
		links.click(showModal);		
		links.hover(onLinkOver, onLinkOut);

	})();

};


KOA.Contact = function() {

	var section         = $(this);
    var html            = $('<form method="post" action="/contact" class="contact-form" accept-charset="UTF-8">'
                        + '<input name="utf8" type="hidden" value="✓">'
                        + '<input name="form_type" type="hidden" value="contact"/>'
                        + '<div class="col1">'
                        + '<div class="dropdown">'
                        + '<select name="contact[inquiry]" default="Select Your Inquiry">'
                            + '<option>Distributor</option>'
                            + '<option>General Questions</option>'
                        + '</select>'
                        + '</div>'
                        + '<div class="field"><input type="text" name="contact[name]" default="Name" /></div>'
                        + '<div class="field"><input type="text" name="contact[email]" default="Email" class="required" /></div>'
                        + '<div class="form_error hide">Oops, you missed some required fields.</div>'
                        + '</div>'
                        + '<div class="col2">'
                        + '<div class="text"><textarea name="contact[body]" class="required" default="Message"></textarea></div>'
                        + '<a href="#subit" class="send">Send</a>'
                        + '</div>'
                        + '</form>');
    
    var form;
    var form_error;
    var form_submit;


	var onFormSubmit = function(e) {
	    e.preventDefault();
	    
	    var errors = false;
	    
	    // Reset error states
	    html.find('DIV.error').removeClass('error');
	    form_error.hide();
    
        // Check all required fields
        html.find('.required').each(function() {
            if (!$(this).val().length || ($(this).val() == $(this).attr('default'))) {
                errors = true;
                $(this).parent().addClass('error');
            }        
        });
        
        // Check valid email
        
        // Should we submit?	    
	    if (errors) {
    	    form_error.fadeIn().fadeOut().fadeIn().fadeOut().fadeIn();
	    } else {
	        jQuery.post(form.attr('action'), form.serialize());
	        form.hide();
    	    section.find('.form .thanks').show();
	    }
	
	};

	
	// Initialize
	return (function() {

        // Init form actions
        KOA.Utils.initDefaultInput(html);
	    html.find('SELECT').SelectStyle();

	    section.find('.form').append(html);

        form            = section.find('FORM');
        form_error      = section.find('.form_error');
        form_submit     = section.find('.send');
        
	    form_submit.click(onFormSubmit);	
	    form.submit(onFormSubmit);	        
	    
	})();

};


KOA.Buy = function() {

	var form			= $(this).find('.form');
	var price_amount	= form.find('.price STRONG');
	var price_period	= form.find('.price EM');
	var dropdowns		= form.find('.dropdown');
	var form_error		= form.find('.form_error');
	
	var products		= {
		265790144 : {title: 'One Time Order', price: '59.99', period: 'per case'}
		, 265790214 : {title: 'Pre-Pay 3-Month', price: '156.57', period: 'per 3 months'}
		, 265790236 : {title: 'Pre-Pay 6-Month', price: '298.75', period: 'per 6 months'}
		, 265790248 : {title: 'Pre-Pay Annual', price: '575.90', period: 'per year'}	
		};

	var onSubscriptionChange = function() {
	
		var product_id = $(this).val();
		
		if (products[product_id]) {
			price_amount.html('$' + products[product_id]['price'] + ' /');
			price_period.html(products[product_id]['period']);
		}		
	
	};
	
	var addToCart = function(e) {
		e.preventDefault();
		e.stopPropagation();
		
		var has_error = false;
        
        form_error.hide();
        
		dropdowns.removeClass('error');
		
		dropdowns.each(function(){	    
		    var select = $(this).find('SELECT');
			if (!select.val().length) {
				has_error = true;
				$(this).addClass('error');
			}
		});
	
		if (has_error) {
    	    form_error.fadeIn().fadeOut().fadeIn().fadeOut().fadeIn();
		} else {
			form.find('FORM').submit();
		}
	
	};
	
	// Initialize
	return (function() {
	
		dropdowns.find('SELECT').SelectStyle();
		
		form.find('.add').click(addToCart);
		form.find('SELECT[name="id"]').change(onSubscriptionChange);

	})();
	
};



